package com.study.forumsystemproject.utils;
import com.study.forumsystemproject.common.Result;
import com.study.forumsystemproject.constant.Constants;
import com.study.forumsystemproject.exception.ApplicationException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * program: forum-system-project
 * <p>
 * description: 令牌工具类
 * <p>
 * author: xiaoxie
 * <p>
 * create: 2024-08-15 21:55
 **/
@Slf4j
public class JwtUtil {
    //将密钥转换为key类型的
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(Constants.secretKey));
    private static final JwtParser parser = Jwts.parserBuilder().setSigningKey(key).build();
    /**
     * Description: 创建Jwt令牌
     * Param: Jwt存储的参数
     * return: Jwt令牌
     * Author: xiaoxie
     * Date: 22:39 2024/8/15
    */
    public static String createJwt(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims)
                .signWith(key)
                .setExpiration(new Date(System.currentTimeMillis() + Constants.expiration))
                .compact();
    }
    /**
     * Description: 解析令牌
     * Param: Jwt令牌
     * return: Jwt令牌存储的数据
     * Author: xiaoxie
     * Date: 22:43 2024/8/15
    */
    public static Claims verifyJwt(String token) {
        if (token == null || token.isEmpty()) {
            throw new IllegalArgumentException("Token cannot be null or empty");
        }
        //根据密钥创建一个对象用来解析令牌
        Claims claims = null;
        try {
            //根据Token解析Token传输的对象.
            claims = parser.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            log.warn("token过期, 校验失败, token:" + token);
        } catch (Exception e) {
            log.error("token校验失败, token:" + token);
        }
        return claims;
    }
    /**
     * Description:getValue
     * Param: request,head,key
     * return: value
     * Author: xiaoxie
     * Date: 18:27 2024/8/18
    */
    public static Object getValue(HttpServletRequest request, String key) {
        String userTokenHeader = request.getHeader("user_token_header");
        Claims claims = JwtUtil.verifyJwt(userTokenHeader);
        return claims.get(key);
    }

}
